import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    // 用户信息
    user: JSON.parse(sessionStorage.getItem('user')) || null,
    token: sessionStorage.getItem('token') || '',
    // 购物车信息
    cart: JSON.parse(sessionStorage.getItem('cart')) || [],
    // 当前选择的商家
    currentMerchant: null,
    // 当前选择的地址
    currentAddress: null
  },
  mutations: {
    // 设置用户信息
    SET_USER_INFO(state, data) {
      state.user = data.user
      state.token = data.token
      sessionStorage.setItem('user', JSON.stringify(data.user))
      sessionStorage.setItem('token', data.token)
    },
    // 设置购物车数据
    SET_CART(state, cartData) {
      state.cart = cartData
      sessionStorage.setItem('cart', JSON.stringify(cartData))
    },
    // 清除用户信息
    CLEAR_USER_INFO(state) {
      state.user = null
      state.token = ''
      sessionStorage.removeItem('user')
      sessionStorage.removeItem('token')
    },
    // 设置当前商家
    SET_CURRENT_MERCHANT(state, merchant) {
      state.currentMerchant = merchant
    },
    // 设置当前地址
    SET_CURRENT_ADDRESS(state, address) {
      state.currentAddress = address
    },
    // 添加商品到购物车
    ADD_TO_CART(state, item) {
      // 检查是否已经在购物车中
      const index = state.cart.findIndex(cartItem => 
        cartItem.foodId === item.foodId && cartItem.merchantId === item.merchantId
      )
      
      if (index > -1) {
        // 如果已存在，增加数量
        state.cart[index].quantity += item.quantity
      } else {
        // 如果不存在，添加到购物车
        state.cart.push(item)
      }
      
      // 保存到本地存储
      sessionStorage.setItem('cart', JSON.stringify(state.cart))
    },
    // 更新购物车商品数量
    UPDATE_CART_ITEM_QUANTITY(state, { id, quantity }) {
      const index = state.cart.findIndex(item => item.id === id)
      if (index > -1) {
        state.cart[index].quantity = quantity
        sessionStorage.setItem('cart', JSON.stringify(state.cart))
      }
    },
    // 从购物车中移除商品
    REMOVE_FROM_CART(state, id) {
      state.cart = state.cart.filter(item => item.id !== id)
      sessionStorage.setItem('cart', JSON.stringify(state.cart))
    },
    // 清空购物车
    CLEAR_CART(state) {
      state.cart = []
      sessionStorage.removeItem('cart')
    },
    // 根据商家ID清空购物车
    CLEAR_MERCHANT_CART(state, merchantId) {
      state.cart = state.cart.filter(item => item.merchantId !== merchantId)
      sessionStorage.setItem('cart', JSON.stringify(state.cart))
    }
  },
  actions: {
    // 登录
    login({ commit, dispatch }, userData) {
      return new Promise((resolve, reject) => {
        Vue.prototype.$http.post('/api/users/login', userData)
          .then(response => {
            const data = response.data.data
            commit('SET_USER_INFO', data)
            // 登录成功后获取购物车数据
            dispatch('getCartList')
            resolve(response)
          })
          .catch(error => {
            reject(error)
          })
      })
    },
    // 获取购物车列表
    getCartList({ commit, state }) {
      if (!state.user) return Promise.resolve([])
      
      return new Promise((resolve, reject) => {
        Vue.prototype.$http.get(`/api/cart/detail/${state.user.id}`)
          .then(response => {
            if (response.data.code === 200) {
              const cartData = response.data.data
              commit('SET_CART', cartData)
              resolve(cartData)
            } else {
              reject(response.data.message)
            }
          })
          .catch(error => {
            reject(error)
          })
      })
    },
    // 注册
    register({ commit }, userData) {
      return new Promise((resolve, reject) => {
        Vue.prototype.$http.post('/api/users/register', userData)
          .then(response => {
            resolve(response)
          })
          .catch(error => {
            reject(error)
          })
      })
    },
    // 登出
    logout({ commit }) {
      commit('CLEAR_USER_INFO')
    }
  },
  getters: {
    // 是否已登录
    isLoggedIn: state => !!state.token,
    // 当前用户
    currentUser: state => state.user,
    // 用户角色
    userRole: state => state.user ? state.user.role : null,
    // 购物车中的商品总数
    cartItemCount: state => {
      return state.cart.reduce((total, item) => total + item.quantity, 0)
    },
    // 购物车中特定商家的商品
    cartItemsByMerchant: state => merchantId => {
      return state.cart.filter(item => item.merchantId === merchantId)
    },
    // 购物车中特定商家的商品总价
    cartTotalByMerchant: (state, getters) => merchantId => {
      const items = getters.cartItemsByMerchant(merchantId)
      return items.reduce((total, item) => total + item.price * item.quantity, 0)
    }
  }
}) 